package dao

import (
	dom "a-common/domain"
	"a-demo/domain/entity"
	"strings"
	"sync"
)

var (
	senBabyDaoTemp *SenBabyDao
	senBabyDaoOnce sync.Once
)

type SenBabyDao struct{}

func NewSenBabyDao() *SenBabyDao {
	senBabyDaoOnce.Do(func() {
		senBabyDaoTemp = &SenBabyDao{}
	})
	return senBabyDaoTemp
}

// List 分页
func (m *SenBabyDao) List(args *entity.SenBabyDto, isExprot bool) (dom.PageVo, error) {
	// 构建查询条件
	query := pgCli.Table(&entity.SenBaby{}).Where("1 = 1")
	if args.BabyCode != "" {
		query.And("room_no = ?", args.BabyCode)
	}
	if args.BabyName != "" {
		query.And("room_name = ?", args.BabyName)
	}
	if args.Status != "" {
		query.And("status = ?", args.Status)
	}
	if args.PageSize != 0 {
		query.Limit(args.PageSize, (args.PageNum-1)*args.PageSize)
	}

	// 查询
	var vPage dom.PageVo
	if isExprot {
		var rows []entity.SenBabyExportVo
		total, err := query.Asc("room_id").FindAndCount(&rows)
		if err != nil {
			return vPage, err
		}
		vPage.Rows = rows
		vPage.Total = total
	} else {
		var rows []entity.SenBabyPageVo
		total, err := query.Asc("room_id").FindAndCount(&rows)
		if err != nil {
			return vPage, err
		}
		vPage.Rows = rows
		vPage.Total = total
	}
	vPage.PageNum = args.PageNum
	vPage.PageSize = args.PageSize
	return vPage, nil
}

// Del 删
func (m *SenBabyDao) Del(ids string) (int64, error) {
	return pgCli.In("room_id", strings.Split(ids, `,`)).Delete(&entity.SenBaby{})
}

// Get 查
func (m *SenBabyDao) Get(id string) (entity.SenBabyVo, error) {
	var v entity.SenBabyVo
	_, err := pgCli.Table(&entity.SenBaby{}).ID(id).Get(&v)
	return v, err
}

// Add 增
func (m *SenBabyDao) Add(args *entity.SenBabyDto) (int64, error) {
	return pgCli.InsertOne(&entity.SenBaby{
		BabyCode: args.BabyCode,
		BabyName: args.BabyName,
		BabySort: args.BabySort,
		Status:   args.Status,
		BaseStruct: dom.BaseStruct{
			CreatedBy: args.CreatedBy,
			UpdatedBy: args.CreatedBy,
			Remark:    args.Remark,
		},
	})
}

// Edit 改
func (m *SenBabyDao) Edit(args *entity.SenBabyDto) (int64, error) {
	return pgCli.ID(args.BabyId).Update(&entity.SenBaby{
		BabyCode: args.BabyCode,
		BabyName: args.BabyName,
		BabySort: args.BabySort,
		Status:   args.Status,
		BaseStruct: dom.BaseStruct{
			UpdatedBy: args.UpdatedBy,
			Remark:    args.Remark,
		},
	})
}
